package itrans;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.*;

public class Register extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("Registration page doesn't support this");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		process(request, response);
	}
	
	public void process(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		String registered = "true";
		HttpSession session = request.getSession(true);
		UserBean userBean = (UserBean) session.getAttribute(PublicConstants.USERBEAN_ATTR);
		
		String username = userBean.getUsername();
		String password = userBean.getPassword();
		String firstName = userBean.getFirstName();
		String lastName = userBean.getLastName();
		String email = userBean.getEmail();
		String phone = userBean.getPhone();
		
		if (checkUserExists(username))
		{
			registered = "false";
		}
		if (checkEmailExists(email))
		{
			registered = "false";
		}
		
		// All checks passed, let's create new user
		if (registered == "true")
			createUser(username, password, firstName, lastName, email, phone);
		
		session.setAttribute("registered", registered);
		request.getRequestDispatcher("/WEB-INF/post_register.jsp").forward(request, response);
	}
	
	public boolean checkRecordExists(String field, String arg)
	{
		Connection con;
		boolean exists = false;
		String searchQuery = "SELECT * FROM Users WHERE " + field + " = ?";
		try {
			DataSource dbcp = (DataSource)getServletContext().getAttribute("dbpool");
            con = dbcp.getConnection();
			PreparedStatement query = con.prepareStatement(searchQuery);
			query.setString(1, arg);
			ResultSet rs = query.executeQuery();
			
			// it's not empty
			if (rs.next()){
				exists = true;
			}
			
			rs.close();
			query.close();
			con.close();
		}
		catch(SQLException ex) {
          System.err.println("SQLException: " + ex.getMessage());
        }
        catch (Exception e) {
          e.printStackTrace();
        }
        return exists;
	}
	
	public boolean checkUserExists(String username)
	{		
		return checkRecordExists("username", username);
	}
	
	public boolean checkEmailExists(String email)
	{
		return checkRecordExists("email", email);
	}
	
	public void createUser(String username, String password, String firstName, String lastName, String email, String phone)
	{
		String query;
		int rowsAffected;
		Connection con;
		try {
			DataSource dbcp = (DataSource)getServletContext().getAttribute("dbpool");
            con = dbcp.getConnection();
			Statement stmt = con.createStatement();
			// drop it if it exists			
			
			query = "INSERT INTO Users "
				  + "(username, password, first_name, last_name, email, phone) "
				  + "VALUES ('" + username + "', '" + password + "',"
				  + "'" + firstName + "', '" + lastName + "', "
				  + "'" + email + "', '" + phone + "');";
			
			rowsAffected = stmt.executeUpdate(query);
		}
		catch(SQLException ex) {
		  System.err.println("SQLException: " + ex.getMessage());
		}
		catch (Exception e) {
		  e.printStackTrace();
		}
	}
}
